#!/usr/bin/env python3
"""
Frontend Server - Serve the HTML frontend with CORS support
"""

import os
import asyncio
from pathlib import Path
from fastapi import FastAPI, Response
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

# Create FastAPI app
app = FastAPI(title="Event Contract Frontend Server")

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Get the project root directory
PROJECT_ROOT = Path(__file__).parent

@app.get("/", response_class=HTMLResponse)
async def serve_index():
    """Serve the main index.html file"""
    index_path = PROJECT_ROOT / "frontend" / "index.html"
    if index_path.exists():
        return FileResponse(index_path, media_type="text/html")
    else:
        return HTMLResponse("<h1>Frontend not found</h1>", status_code=404)

@app.get("/styles.css")
async def serve_styles():
    """Serve the styles.css file"""
    css_path = PROJECT_ROOT / "frontend" / "styles.css"
    if css_path.exists():
        return FileResponse(css_path, media_type="text/css")
    else:
        return Response("CSS file not found", status_code=404)

@app.get("/script.js")
async def serve_script():
    """Serve the script.js file"""
    js_path = PROJECT_ROOT / "frontend" / "script.js"
    if js_path.exists():
        return FileResponse(js_path, media_type="application/javascript")
    else:
        return Response("JS file not found", status_code=404)

@app.get("/config.js")
async def serve_config():
    """Serve the config.js file"""
    config_path = PROJECT_ROOT / "frontend" / "config.js"
    if config_path.exists():
        return FileResponse(config_path, media_type="application/javascript")
    else:
        return Response("Config file not found", status_code=404)

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "message": "Frontend server is running",
        "backend_websocket": "ws://localhost:8768"
    }

# Mount static files for any additional assets
if (PROJECT_ROOT / "frontend").exists():
    app.mount("/static", StaticFiles(directory=PROJECT_ROOT / "frontend"), name="static")

def main():
    """Main function to start the frontend server"""
    print("=" * 60)
    print("🌐 Event Contract Platform - Frontend Server")
    print("=" * 60)
    print("📁 Serving frontend from: frontend/index.html")
    print("🔗 Frontend URL: http://localhost:8000")
    print("🔗 Backend WebSocket: ws://localhost:8768")
    print("💾 localStorage support: ✅ Enabled")
    print()
    print("📖 Instructions:")
    print("1. First, start the backend server:")
    print("   python demo_server.py")
    print()
    print("2. Then open your browser and go to:")
    print("   http://localhost:8000")
    print()
    print("3. Create a user account and start trading!")
    print("=" * 60)
    print()
    
    uvicorn.run(
        "frontend_server:app",
        host="0.0.0.0",
        port=8000,
        reload=False,
        log_level="info"
    )

if __name__ == "__main__":
    main()
